<template>
  <div class="add-color-container">
    <div class="header">
      <h2>{{ isEdit ? '编辑颜色' : '添加颜色' }}</h2>
      <button class="btn btn-secondary" @click="goBack">
        <i class="icon">←</i>
        返回
      </button>
    </div>

    <div class="form-container">
      <form @submit.prevent="submitForm" class="color-form">
        <div class="form-row">
          <div class="form-group">
            <label for="name">颜色名称 *</label>
            <input
              type="text"
              id="name"
              v-model="form.name"
              placeholder="请输入颜色名称"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="hexCode">颜色代码 *</label>
            <div class="color-input-group">
              <input
                type="text"
                id="hexCode"
                v-model="form.hexCode"
                placeholder="#000000"
                pattern="^#[0-9A-Fa-f]{6}$"
                required
              />
              <input
                type="color"
                v-model="form.hexCode"
                class="color-picker"
                title="选择颜色"
              />
            </div>
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="category">颜色分类</label>
            <select id="category" v-model="form.category">
              <option value="">选择分类（可选）</option>
              <option value="basic">基础色</option>
              <option value="bright">亮色系</option>
              <option value="dark">深色系</option>
              <option value="pastel">淡色系</option>
              <option value="metallic">金属色</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="sortOrder">排序</label>
            <input
              type="number"
              id="sortOrder"
              v-model="form.sortOrder"
              placeholder="排序值（数字越小越靠前）"
              min="0"
            />
          </div>
        </div>

        <div class="color-preview-section">
          <label>颜色预览</label>
          <div class="preview-container">
            <div 
              class="color-preview-large" 
              :style="{ backgroundColor: form.hexCode || '#ffffff' }"
            ></div>
            <div class="preview-info">
              <p><strong>颜色名称：</strong>{{ form.name || '未命名' }}</p>
              <p><strong>颜色代码：</strong>{{ form.hexCode || '#ffffff' }}</p>
              <p><strong>RGB值：</strong>{{ getRgbValue() }}</p>
            </div>
          </div>
        </div>

        <div class="form-group full-width">
          <label for="description">颜色描述</label>
          <textarea
            id="description"
            v-model="form.description"
            placeholder="请输入颜色描述"
            rows="3"
          ></textarea>
        </div>

        <div class="form-actions">
          <button type="button" class="btn btn-secondary" @click="goBack">
            取消
          </button>
          <button type="submit" class="btn btn-primary">
            {{ isEdit ? '更新颜色' : '创建颜色' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AddColor',
  props: {
    colorData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      form: {
        name: '',
        hexCode: '#000000',
        category: '',
        description: '',
        sortOrder: 0
      }
    };
  },
  computed: {
    isEdit() {
      return this.colorData !== null;
    }
  },
  watch: {
    colorData: {
      immediate: true,
      handler(newData) {
        if (newData) {
          this.form = {
            name: newData.name || '',
            hexCode: newData.hex || newData.hexCode || '#000000',
            category: newData.category || '',
            description: newData.description || '',
            sortOrder: newData.sortOrder || 0
          };
        } else {
          this.resetForm();
        }
      }
    }
  },
  methods: {
    submitForm() {
      if (!this.validateForm()) {
        return;
      }

      // 模拟API调用
      setTimeout(() => {
        if (this.isEdit) {
          this.showToast('颜色更新成功！', 'success');
        } else {
          this.showToast('颜色创建成功！', 'success');
        }
        
        setTimeout(() => {
          this.goBack();
        }, 1000);
      }, 500);
    },

    validateForm() {
      if (!this.form.name.trim()) {
        this.showToast('请输入颜色名称', 'error');
        return false;
      }

      if (!this.form.hexCode) {
        this.showToast('请输入颜色代码', 'error');
        return false;
      }

      if (!/^#[0-9A-Fa-f]{6}$/.test(this.form.hexCode)) {
        this.showToast('请输入有效的颜色代码（如：#000000）', 'error');
        return false;
      }

      return true;
    },

    getRgbValue() {
      if (!this.form.hexCode || !/^#[0-9A-Fa-f]{6}$/.test(this.form.hexCode)) {
        return 'rgb(255, 255, 255)';
      }
      
      const hex = this.form.hexCode.substring(1);
      const r = parseInt(hex.substring(0, 2), 16);
      const g = parseInt(hex.substring(2, 4), 16);
      const b = parseInt(hex.substring(4, 6), 16);
      
      return `rgb(${r}, ${g}, ${b})`;
    },

    resetForm() {
      this.form = {
        name: '',
        hexCode: '#000000',
        category: '',
        description: '',
        sortOrder: 0
      };
    },

    goBack() {
      this.$emit('navigate', '颜色管理');
    },

    showToast(message, type = 'info') {
      const toast = document.createElement('div');
      toast.className = `toast toast-${type}`;
      toast.textContent = message;
      
      Object.assign(toast.style, {
        position: 'fixed',
        top: '20px',
        right: '20px',
        padding: '12px 20px',
        borderRadius: '6px',
        color: 'white',
        fontSize: '14px',
        fontWeight: '500',
        zIndex: '10000',
        opacity: '0',
        transform: 'translateX(100%)',
        transition: 'all 0.3s ease',
        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.2)'
      });

      const colors = {
        success: '#10b981',
        error: '#ef4444',
        warning: '#f59e0b',
        info: '#3b82f6'
      };
      
      toast.style.background = colors[type] || colors.info;
      document.body.appendChild(toast);
      
      setTimeout(() => {
        toast.style.opacity = '1';
        toast.style.transform = 'translateX(0)';
      }, 100);
      
      setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(100%)';
        setTimeout(() => {
          if (document.body.contains(toast)) {
            document.body.removeChild(toast);
          }
        }, 300);
      }, 3000);
    }
  }
};
</script>

<style scoped>
.add-color-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.header h2 {
  margin: 0;
  color: #1f2937;
  font-size: 24px;
  font-weight: 600;
}

.form-container {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.color-form {
  max-width: 800px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 12px 16px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.2s ease;
  background: white;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.color-input-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.color-input-group input[type="text"] {
  flex: 1;
}

.color-picker {
  width: 50px;
  height: 44px;
  padding: 0;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  cursor: pointer;
}

.color-preview-section {
  margin: 30px 0;
  padding: 20px;
  background: #f9fafb;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
}

.color-preview-section label {
  display: block;
  margin-bottom: 16px;
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.preview-container {
  display: flex;
  gap: 20px;
  align-items: center;
}

.color-preview-large {
  width: 120px;
  height: 120px;
  border-radius: 12px;
  border: 2px solid #e5e7eb;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.preview-info {
  flex: 1;
}

.preview-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #6b7280;
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  text-decoration: none;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-primary:hover {
  background: #2563eb;
  transform: translateY(-1px);
}

.btn-secondary {
  background: #6b7280;
  color: white;
}

.btn-secondary:hover {
  background: #4b5563;
  transform: translateY(-1px);
}

.icon {
  font-style: normal;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-color-container {
    padding: 15px;
  }
  
  .form-container {
    padding: 20px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .preview-container {
    flex-direction: column;
    text-align: center;
  }
  
  .form-actions {
    flex-direction: column-reverse;
  }
  
  .btn {
    width: 100%;
    justify-content: center;
  }
}
</style>